
(function($) {
    var D = $(document).data('func', {});
    $.smartMenu = $.noop;
    $.fn.smartMenu = function(data, options) {
        var B = $('body'), defaults = {
            name: '',
            container:'',
            offsetX: 2,
            offsetY: 2,
            textLimit: 6,
            beforeShow: $.noop,
            afterShow: $.noop
        };
        var params = $.extend(defaults, options || {});

        var htmlCreateMenu = function(datum) {
            var dataMenu = datum || data, nameMenu = datum? 'ziji': params.name, htmlMenu = "", htmlCorner = "", clKey = 'smart_menu_';
            
            if ($.isArray(dataMenu) && dataMenu.length) {
				
            	htmlMenu = '<div id="smartMenu_'+ nameMenu +'" class="'+ clKey +'box">' +
					'<div class="'+ clKey +'body">' +
					'<ul class="'+ clKey +'ul">';
                $.each(dataMenu, function(i, arr) {
                    if (i) {
                        htmlMenu = htmlMenu + '<li class="'+ clKey +'li_separate">&nbsp;</li>';
                    }
                    if ($.isArray(arr)) {
                        $.each(arr, function(j, obj) {
                            var text = obj.text, htmlMenuLi = '', strTitle = '', rand = Math.random().toString().replace('.', '');
                            if (text) {
                                if (text.length > params.textLimit) {
                                    text = text.slice(0, params.textLimit)	+ '...';
                                    strTitle = ' title="'+ obj.text +'"';
                                }
                                htmlMenuLi = '<li class="'+ clKey +'li">' +
                                    '<a href="javascript:" class="'+ clKey +'a"'+ strTitle +' data-key="'+ rand +'"><span>'+ text +'</span></a>' +
                                    '</li>';
                                htmlMenu += htmlMenuLi;

                                var objFunc = D.data('func');
                                objFunc[rand] = obj.func;
                                D.data('func', objFunc);
                            }
                        });
                    }
                });
                htmlMenu = htmlMenu + '</ul>';
            }
            
            var childMenu='';
            
            $.each(dataMenu, function(i, arr) {
     			
            	if ($.isArray(arr)) {
            		
            		$.each(arr, function(j, obj) {
            			var abc='';
            			
            			childMenu+='<ul class="p'+j+' p_item" id="p'+j+'">';
            			if ($.isArray(obj.data) && obj.data.length) {
            				
            				var arrData=obj.data[0];
            				
            				for(var k=0;k<arrData.length;k++){
            					var rand = Math.random().toString().replace('.', '');
            					childMenu+='<li class="'+ clKey +'li_zj">' +
                                        '<a href="javascript:" class="'+ clKey +'a_zj" data-key="'+ rand +'"><span>'+ arrData[k]["text"] +'</span></a>' +
                                        '</li>';
                                
                                var objFunc = D.data('func');
                                objFunc[rand] = arrData[k].func;
                                D.data('func', objFunc);
            				}
            				
            			}
            			childMenu+='</ul>';
            		})
            	
            	}
            
            })
            
            childMenu+='</div></div>';
            
            return htmlMenu+childMenu;
            
        }, funSmartMenu = function() {
            //TODO 修改为事件代理
            var idKey = '#smartMenu_', clKey = 'smart_menu_', jqueryMenu = $(idKey + params.name);
            if (!jqueryMenu.length) {
                $('#relationBox').append(htmlCreateMenu());

                //事件
                $(idKey + params.name +' a').bind('click', function() {
                    var key = $(this).attr('data-key'),
                        callback = D.data('func')[key];
                    if ($.isFunction(callback)) {
                        callback.call(D.data('trigger'));
                    }
                    $.smartMenu.hide();
                    return false;
                });
                $(idKey + params.name +' li').each(function() {
                    var isHover = $(this).attr('data-hover'), clHover = clKey + 'li_hover';

                    $(this).hover(function() {
                        var jqueryHover = $(this).siblings("." + clHover);
                        jqueryHover.removeClass(clHover).children("."+ clKey +'box').hide();
                        jqueryHover.children('.'+ clKey +'a').removeClass(clKey +'a_hover');

                        if (isHover) {
                            $(this).addClass(clHover).children("."+ clKey +'box').show();
                            $(this).children('.'+ clKey +'a').addClass(clKey +'a_hover');
                        }

                    });

                });
                
                $(idKey+params.name +' ul.smart_menu_ul li').each(function(i){
                	$(this).find('span').on('mouseenter',function(){
                		
                		$(idKey+params.name+' ul.p'+i).addClass('dishow').siblings().removeClass('dishow');
                	});
                	$(this).parents('.smart_menu_body').on('mouseleave',function(){
                		$(idKey+params.name+" ul.p"+i).removeClass('dishow');
                	});
                });
                
                
                return $(idKey + params.name);
            }
            return jqueryMenu;
        };

        $(this).on('contextmenu',params.container,function(e){
                    if ($.isFunction(params.beforeShow)) {
                        params.beforeShow.call(this);
                    }
                    e = e || window.event;
                    //阻止冒泡
                    e.cancelBubble = true;
                    if (e.stopPropagation) {
                        e.stopPropagation();
                    }
                    //隐藏当前上下文菜单，确保页面上一次只有一个上下文菜单
                    $.smartMenu.hide();
                    var st = D.scrollTop();
                    var jqueryMenu = funSmartMenu();
					
					/*var xx=$('input[name=posx]').val(),yy=$('input[name=posy]').val();
					console.log('aaaa:'+posx+','+yy)*/
					console.log(posx);
                    if (jqueryMenu) {
                        jqueryMenu.css({
                            //display: "block",
                            left: posx,//e.clientX + params.offsetX,
                            top: posy//e.clientY + st + params.offsetY
                        }).fadeIn(200);
                        D.data('target', jqueryMenu);
                        D.data('trigger', this);
                        //回调
                        if ($.isFunction(params.afterShow)) {
                            params.afterShow.call(this);
                        }
                        return false;
                    }
					
        });
        if (!B.data('bind')) {
            B.bind('click', $.smartMenu.hide).data('bind', true);
        }
    };
    $.extend($.smartMenu, {
        hide: function() {
            var target = D.data('target');
            if (target && target.css('display') === 'block') {
                target.hide();
            }
        },
        remove: function() {
            var target = D.data('target');
            if (target) {
                target.remove();
            }
        }
    });
})(jQuery);
